package com.cn.demo4.servlet.admin.news;

import com.alibaba.fastjson.JSONObject;
import com.cn.demo4.model.NewsModel;
import com.cn.demo4.model.PageModel;
import com.cn.demo4.service.INewsService;
import com.cn.demo4.service.impl.NewsServiceImpl;
import com.cn.demo4.util.Tool;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/admin/news/findAll")
public class NewsFindAllServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        //调用服务层
        String title = req.getParameter("title");
        String newsType = req.getParameter("newsType");
        String status = req.getParameter("status");
        status = status == null ? "-1" : status;
        String publisher = req.getParameter("publisher");
        String curPage = req.getParameter("curPage");
        String pageSize = req.getParameter("pageSize");

        NewsModel newsModel = new NewsModel();
        newsModel.setPublisher(publisher);
        newsModel.setStatus(Tool.stringToInt(status));
        newsModel.setTypeName(newsType);
        newsModel.setTitle(title);

        PageModel pageModel = new PageModel();
        pageModel.setCurPage(Tool.toCurPage(curPage));
        pageModel.setPageSize(Tool.toPageSize(pageSize));
        newsModel.setPageModel(pageModel);

        INewsService iNewsService = new NewsServiceImpl();
        //定义一个集合接受数据
        List<NewsModel> list = iNewsService.findAll(newsModel);
        int count = iNewsService.getCount(newsModel);

        //返回结果到前台
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list",list);
        jsonObject.put("count",count);
        resp.getWriter().println(jsonObject);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      this.doGet(req,resp);
    }
}
